package com.fitns.user.service.baseConfig;

import com.fitns.user.constant.Constants;
import com.fitns.user.conf.ExcelConstants;
import com.fitns.user.dao.baseConfig.TbFacilityDataDao;
import com.fitns.user.dao.baseConfig.TbFacilityTypeDao;
import com.fitns.user.dto.baseConfig.*;
import com.fitns.user.exception.FacilityDataMsgCode;
import com.fitns.user.exception.ServiceException;
import com.fitns.user.model.baseConfig.TbFacilityData;
import com.fitns.user.model.baseConfig.TbFacilityType;
import com.fitns.user.utils.DateUtil;
import com.github.pagehelper.PageInfo;
import com.xiaoleilu.hutool.lang.Validator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *Created by zhou on 2018/7/20
 *
 */

@Service
public class FacilityDataService {

    @Autowired
    private TbFacilityDataDao facilityDataDao;

    @Autowired
    private TbFacilityTypeDao facilityTypeDao;


    public List<TbFacilityData> searchByAreaAndType(TbFacilityData tbFacilityData){
        return null;
    }

    public PageInfo<TbFacilityData> search(FacilityDataCondition tbFacilityData) {
        if(StringUtils.isEmpty(tbFacilityData)){
            return null;
        }
        //PageHelper.startPage(tbFacilityData.getPageNum(),tbFacilityData.getPageSize());
        List<TbFacilityData> tbFacilityDataList= facilityDataDao.search(tbFacilityData);
        PageInfo<TbFacilityData> pageInfo=new PageInfo<>(tbFacilityDataList);

        return pageInfo;
    }

    public PageInfo<FaciltyTypeVo> searchFor(FacilityDataCondition facilityDataCondition) {
        List<TbFacilityType> tbFacilityDatas=facilityTypeDao.search(facilityDataCondition);
        List<FaciltyTypeVo> typeVoList=new ArrayList<>();
        if(Validator.isNotNull(tbFacilityDatas)) {
            tbFacilityDatas.forEach(tbFacilityType->{
                List<TbFacilityData> tbFacilityDataList = new ArrayList<>();
                FaciltyTypeVo faciltyTypeVo = new FaciltyTypeVo();
                BeanUtils.copyProperties(tbFacilityType, faciltyTypeVo);
                FacilityDataCondition dataCondition = new FacilityDataCondition();
                dataCondition.setFacilityType(tbFacilityType.getFacilityType());
                tbFacilityDataList = facilityDataDao.search(dataCondition);
                if (Validator.isNotNull(tbFacilityDataList)) {
                    faciltyTypeVo.setNumber(tbFacilityDataList.size());
                } else {
                    faciltyTypeVo.setNumber(0);
                }
                typeVoList.add(faciltyTypeVo);
            });
        }
        PageInfo<FaciltyTypeVo> faciltyTypeVoPageInfo=new PageInfo<>(typeVoList);
        return faciltyTypeVoPageInfo;
    }

    public FacilityDataVO findDetailed(FacilityDataCondition tbFacilityData) {
        if(StringUtils.isEmpty(tbFacilityData)){
            return null;
        }
        FacilityDataVO facilityDataVO=new FacilityDataVO();
        TbFacilityData facilityData=new TbFacilityData();
        if(StringUtils.isEmpty(tbFacilityData.getId())){//根据经纬度查询
            if(!StringUtils.isEmpty(tbFacilityData.getLgitude())&&
                    !StringUtils.isEmpty(tbFacilityData.getLatitude())){
                List<TbFacilityData> tbFacilityDatalist= facilityDataDao.search(tbFacilityData);
                if(StringUtils.isEmpty(tbFacilityDatalist)){
                    return null;
                }
                facilityData= tbFacilityDatalist.get(0);
                BeanUtils.copyProperties(facilityData,facilityDataVO);
                String date=DateUtil.parseTimestampToStr(facilityData.getBeginTime(),Constants.DATESTR2);
                facilityDataVO.setBeginTime1(date);
                return facilityDataVO;
            }
        }else {
               facilityData= facilityDataDao.select(tbFacilityData.getId());


               if(Validator.isNotNull(facilityData.getBeginTime())) {
                   String date = DateUtil.parseTimestampToStr(facilityData.getBeginTime(), Constants.DATESTR2);
                   facilityDataVO.setBeginTime1(date);
               }

            BeanUtils.copyProperties(facilityData,facilityDataVO);
            return facilityDataVO;
        }

        return null;
    }

    public void validate(FacilityDataVO facilityData){
        if(Validator.isNull(facilityData.getBeginTime())){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_BAGANTIME_IS_NULL);
        }
        if(Validator.isNull(facilityData.getAddress())){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_ADDRESS);

        }
        if(Validator.isNull(facilityData.getName())){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_AME);

        }
        if(Validator.isNull(facilityData.getStatus())){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_AME);
        }
    }

    public TbFacilityData insert(FacilityDataVO facilityData) {
        this.validate(facilityData);
        if(Validator.isNull(facilityData)){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_ORGAN_OR_IS_NULL);
        }

        TbFacilityData tbFacilityData=new TbFacilityData();
        BeanUtils.copyProperties(facilityData,tbFacilityData,FacilityDataVO.FacilityDataFields.BEGAN_TIME.getFieldName());
        String beganTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(facilityData.getBeginTime());
        Timestamp beganTimes=Timestamp.valueOf(beganTime);

        tbFacilityData.setBeginTime(beganTimes);
        String nowDate=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        Timestamp insertDate=Timestamp.valueOf(nowDate);
        tbFacilityData.setCreateTime(insertDate);
        tbFacilityData.setModifyTime(insertDate);
        facilityDataDao.inserts(tbFacilityData);
        return tbFacilityData;
    }

       public Long delete(Long id) {
        if(Validator.isNull(id)){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_ID_IS_NULL);
        }
           TbFacilityData facilityData=facilityDataDao.select(id);
        if(Validator.isNull(facilityData)){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_DATA_IS_NOT_EXIST);
        }
        facilityDataDao.delete(id);
        return id;
    }


    public TbFacilityData modify(TbFacilityData facilityData) {
        if(Validator.isNull(facilityData)){
           throw ServiceException.create(FacilityDataMsgCode.FACILITY_DATA_IS_NULL);
        }
        TbFacilityData tbFacilityData=facilityDataDao.select(facilityData.getId());
        if(Validator.isNull(tbFacilityData)){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_DATA_IS_NOT_EXIST);

        }
        facilityDataDao.update(facilityData);
        return facilityDataDao.select(facilityData.getId());
    }

    @Transactional
    public void deleteByType(Long id,String facilityType) {
        if(Validator.isNull(facilityType)){
            throw ServiceException.create(FacilityDataMsgCode.FACILITY_TYPE_IS_NULL);
        }

        //删除该设施类型
        facilityTypeDao.deleteByType(id);

        //删除该设施类型下的所有设施
        facilityDataDao.deleteByType(facilityType);

    }


    public void inserImage(FacilityDataVO facilityData) {
        TbFacilityData tbFacilityData = new TbFacilityData();
        BeanUtils.copyProperties(facilityData, tbFacilityData);
        if (Validator.isNull(facilityData.getId())) {
            facilityData.setImage(facilityData.getImage());
            //record.setInputTime(new Date());
            this.insert(facilityData);
        } else {
            tbFacilityData.setImage(facilityData.getImage());
            this.modify(tbFacilityData);
        }
    }


    public List<List<String>> export(FacilityDataCondition facilityDataCondition){
        List<TbFacilityData> facilityDataList=facilityDataDao.searchForExport(facilityDataCondition);
        List<List<String>> excelList = new ArrayList<>();
        for (int i = 0; i < facilityDataList.size(); i++) {
            if(i==0){
                excelList.add(this.getRowHeader(ExcelConstants.FACILITY_DATA_IMPORT_HEADER.class));
            }
            excelList.add(this.getrow(facilityDataList.get(i),i));
        }
        return excelList;
    }

    public List<String> getrow(TbFacilityData facilityData, int i){
        List<String> row = new ArrayList<>();
        row.add(String.valueOf(i + 1));
        row.add(facilityData.getName());
        if(Validator.isNull(facilityData.getBeginTime())) {
            row.add("");
        }else {
            row.add(DateUtil.parseDateToStr(facilityData.getBeginTime(),Constants.DATESTR));
        }
        row.add(facilityData.getAddress());
        if(Validator.isNull(facilityData.getStatus())){
            row.add("");
        }else {
            if (facilityData.getStatus() == 0) {
                row.add("报废");
            } else {
                row.add("正常");
            }
        }
        if(Validator.isNull(facilityData.getAcreage())){
            row.add("");
        }else {
            row.add(String.valueOf(facilityData.getAcreage()));
        }
        if(Validator.isNull(facilityData.getPopulation())){
            row.add("");
        }else {
            row.add(String.valueOf(facilityData.getPopulation()));
        }
        row.add(facilityData.getCounter());
        row.add(facilityData.getLiabler());
        row.add(facilityData.getPhone());
        row.add(facilityData.getTerminal());
        row.add(facilityData.getRfid());
        row.add((facilityData.getDescs()));
        row.add(facilityData.getLgitude());
        row.add(facilityData.getLatitude());
        return row;
    }

    public List<String> getRowHeader(Class clazz){
        Field[] fields=clazz.getDeclaredFields();
        List<String> rowHeader = new ArrayList<>();
        for(int i=0;i<fields.length-1;i++){
            try {
                Object object =fields[i].get(clazz);
                String value = object.toString();
                rowHeader.add(value);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return rowHeader;
    }

    @Transactional
    public List<FacilityDataVO> importExcel(List<List<String>> excelList, String facilityType){

        List<FacilityDataVO> dtoList=new ArrayList<>();
        List<FacilityDataVO> msgList=new ArrayList<>();

        for (int i = 1; i <excelList.size() ; i++) {
            String number=excelList.get(i).get(0);
            if(!StringUtils.isEmpty(number)){
                FacilityDataVO facilityDataVO =this.validateExcel(excelList.get(i),i);
                if(!StringUtils.isEmpty(facilityDataVO.getMsg())){
                    msgList.add(facilityDataVO);
                }else {
                    FacilityDataVO dataVo=this.importDetail(excelList.get(i));
                    dtoList.add(dataVo);
                }
            }
        }
        if(Validator.isEmpty(msgList)||msgList.size()==0){
            if(Validator.isNotEmpty(dtoList)&&dtoList.size()!=0){
              //  Map<String, Object> map = new HashMap<>();
                dtoList.forEach(facilityDataVO -> {
                    TbFacilityData facilityData=new TbFacilityData();
                    BeanUtils.copyProperties(facilityDataVO,facilityData);
                    facilityData.setFacilityType(facilityType);
                    facilityDataDao.inserts(facilityData);
                });
               /* map.put("list", dtoList);
                facilityDataDao.insertImport(map);*/
            }else {
                FacilityDataVO facilityDataVO =new FacilityDataVO();
                facilityDataVO.setMsg(ExcelConstants.FACLITY_DATA_IMPORT.EXCEL_IS_NULL);
                msgList.add(facilityDataVO);
            }
        }

        return msgList;

    }

    public FacilityDataVO importDetail(List<String> excelList){
        FacilityDataVO facilityDataVO =new FacilityDataVO();
        facilityDataVO.setName(excelList.get(1));
        if(Validator.isNotNull(excelList.get(2))) {
           facilityDataVO.setBeginTime(DateUtil.parseStrToDate(excelList.get(13), Constants.DATESTR));
        }
        facilityDataVO.setAddress(excelList.get(3));
        if(Validator.isNotNull(excelList.get(4))) {
            facilityDataVO.setStatus(Integer.valueOf(excelList.get(4)));
        }
        if(Validator.isNotNull(excelList.get(5))) {
            facilityDataVO.setAcreage(Float.valueOf(excelList.get(5)));
        }
        if(Validator.isNotNull(excelList.get(6))) {
            facilityDataVO.setPopulation(Integer.valueOf(excelList.get(6)));
        }
        facilityDataVO.setCounter(excelList.get(7));
        facilityDataVO.setLiabler(excelList.get(8));
        facilityDataVO.setPhone(excelList.get(9));
        facilityDataVO.setTerminal(excelList.get(10));
        facilityDataVO.setRfid(excelList.get(11));
        facilityDataVO.setDescs(excelList.get(12));
        facilityDataVO.setLatitude(excelList.get(13));
        facilityDataVO.setLgitude(excelList.get(14));
        return facilityDataVO;
    }

    public FacilityDataVO validateExcel(List<String> excelList, int i){
        FacilityDataVO facilityDataVO =new FacilityDataVO();
        StringBuilder msg = new StringBuilder();
        if(StringUtils.isEmpty(excelList.get(1))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.FACILITY_DATA_NAME_IS_NULL);
        }
        if(StringUtils.isEmpty(excelList.get(2))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.FACILITY_DATA_START_DATE);
        }
        if(StringUtils.isEmpty(excelList.get(2))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.FACILITY_DATA_ADRESS);
        }
        if(StringUtils.isEmpty(excelList.get(2))){
            msg.append("第"+(i+1)+"行"+ExcelConstants.FACLITY_DATA_IMPORT.FACILITY_DATA_STATUS);
        }

        if(!StringUtils.isEmpty(msg)){
            facilityDataVO.setMsg(msg.toString());
        }
        return facilityDataVO;
    }

}
